package club.kingyin.kyblogprouser.controller;



import club.kingyin.commons.clients.CoreClient;
import club.kingyin.commons.entity.core.Document;
import club.kingyin.commons.entity.core.Documents;
import club.kingyin.commons.response.Result;
import club.kingyin.kyblogprouser.dao.LogDao;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import club.kingyin.commons.entity.user.Log;
import club.kingyin.kyblogprouser.service.LogService;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * (Log)表控制层
 *
 * @author makejava
 * @since 2022-01-20 15:04:02
 */
@RestController
@RequestMapping("log")
public class LogController {
    /**
     * 服务对象
     */
    @Resource
    private LogService logService;

    @Resource
    private LogDao logDao;

    @Resource
    private CoreClient coreClient;

    /**
     * 分页查询所有数据
     *
     * @param page 分页对象
     * @param log 查询实体
     * @return 所有数据
     */
    @GetMapping
    public Result selectAll(Page<Log> page, Log log) {
        return Result.success(this.logService.page(page, new QueryWrapper<Log>(log)));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public Result selectOne(@PathVariable Serializable id) {
        return Result.success(this.logService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param log 实体对象
     * @return 新增结果
     */
    @PostMapping
    public Result insert(@RequestBody Log log) {
        return Result.success(this.logService.save(log));
    }

    /**
     * 修改数据
     *
     * @param log 实体对象
     * @return 修改结果
     */
    @PutMapping
    public Result update(@RequestBody Log log) {
        return Result.success(this.logService.updateById(log));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public Result delete(@RequestParam("idList") List<Long> idList) {
        return Result.success(this.logService.removeByIds(idList));
    }

    @PutMapping("/append")
    public Result appendResponse(@RequestBody Log log) {
        Log byId = logService.getById(log.getId());
        JSONObject response = (JSONObject)byId.getResponse();
        JSONObject res = new JSONObject();
        res.put("header",log.getHeader());
        res.put("params",log.getParams());
        res.put("response",log.getResponse());
        res.put("timestamp",log.getTimestamp());
        response.put(log.getUrl(),res);
        return Result.success(logService.updateById(byId));
    }

    // 查看用户的最近十条浏览记录
    @GetMapping("/history")
    public Result watchHistory(@RequestParam("userid") int userid) {
        List<Log> logs = logDao.selectDistinctPramsByUserIdAndUrl(userid, "/document/detail");
        if (logs == null || logs.size() == 0)
            return Result.infoN("还没有阅读记录哦");
        Map<Integer,Long> history = new HashMap<>();
        for (Log log : logs) {
            String prams = StringEscapeUtils.unescapeJava(log.getParams().toString());
            history.put(JSON.parseObject(prams.replace("\"","")).getJSONArray("id").getInteger(0),log.getTimestamp());
        }
        Documents documents = new Documents();
        documents.setIds(history.keySet().toArray(new Integer[0]));
        List<Map<String,Object>> res = (List<Map<String,Object>>) coreClient.getDocByIds(documents).getData();
        for (Map document : res) {
            document.put("timestamp",history.get(document.get("id")));
        }
        return Result.success(res);
    }

    // 统计最近阅读数据
    @GetMapping("/history/all")
    public Result watchHistoryAll(@RequestParam("userid") int userid) {
        List<Log> logs = logDao.selectPramsByUserIdAndUrl(userid, "/document/detail");
        if (logs == null || logs.size() == 0) return Result.failN("无数据");
        Map<Integer,Integer> history = new HashMap<>();
        for (Log log : logs) {
            if (log.getUserid() != null && log.getUserid() == userid) {
                String prams = StringEscapeUtils.unescapeJava(log.getParams().toString());
                Integer id = JSON.parseObject(prams.replace("\"", "")).getJSONArray("id").getInteger(0);
                history.put(id,history.getOrDefault(id,0)+1);
            }
        }
        return history.size()>0?Result.success(history):Result.failN("无有效数据");
    }
}

